package com.nbgs.demo.config;


import com.nbgs.demo.common.EncryptUtil;
import com.nbgs.demo.component.ShiroRealm;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ShiroConfig {
    @Bean
    public CredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(EncryptUtil.ALGORITHM_NAME);
        matcher.setHashIterations(EncryptUtil.HASH_ITERATIONS);
        return matcher;
    }
    /**
     * 自定义Realm 提供数据源
     * @return
     */
    @Bean
    public Realm shiroRealm(){
        ShiroRealm shiroRealm = new ShiroRealm();
        shiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        shiroRealm.setCacheManager(cacheManager());
        //认证缓存默认关闭，打开授权缓存
        shiroRealm.setAuthenticationCachingEnabled(true);

        return shiroRealm;

    }
    @Bean
    public ShiroFilterChainDefinition shiroFilterChainDefinition(){
        DefaultShiroFilterChainDefinition sfcd=new DefaultShiroFilterChainDefinition();
        sfcd.addPathDefinition("/","anon");
        sfcd.addPathDefinition("/login","anon");
        sfcd.addPathDefinition("/add","anon");
        sfcd.addPathDefinition("/css/**","anon");
        sfcd.addPathDefinition("/js/**","anon");
        sfcd.addPathDefinition("/images/**","anon");
        sfcd.addPathDefinition("/fonts/**","anon");
        sfcd.addPathDefinition("/html/**","anon");
        //logout登出
        sfcd.addPathDefinition("/logout","logout");
        //其他则需要认证
        //sfcd.addPathDefinition("/**","user");
        return sfcd;
    }

    @Bean
    public MemoryConstrainedCacheManager cacheManager(){
        return new MemoryConstrainedCacheManager();
    }
}
